/*

  The MIT License

  Copyright (c) 2008 - 2011. Dimarik

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

*/

package ru.goodcore.managers
{

import flash.errors.IllegalOperationError;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.utils.ByteArray;
import flash.utils.Dictionary;

import ru.goodcore.composite.Cradle;
import ru.goodcore.css.CSSParser;
import ru.goodcore.display.ui.core.UIComponent;
import ru.goodcore.text.StyleSheet;
import ru.goodcore.text.StyleTable;
import ru.goodcore.utils.ObjectInfo;

/**
 * StyleManager
 *
 * @author					Dimarik
 * @version					1.0
 * @playerversion			Flash 9
 * @langversion				3.0
 *
 * @keyword					stylemanager, style
 */
public class StyleManager extends EventDispatcher
{

	include "../../../includes/core/Version.as";

	//-------------------------------------------------------------------------
	//
	//  Class constants
	//
	//-------------------------------------------------------------------------

	public static const instance:	StyleManager = new StyleManager();

	private static var _inctanceCreated:	Boolean = false;

	//-------------------------------------------------------------------------
	//
	//  Constructor
	//
	//-------------------------------------------------------------------------

	/**
	 * Constructor
	 */
	public function StyleManager() {
		super();

		if ( !_inctanceCreated ) {
			_inctanceCreated = true;
		} else {
			throw new IllegalOperationError('StyleManager is singleton. Use StyleManager.instance instead instantiation');
		}
	}

	//-------------------------------------------------------------------------
	//
	//  Properties
	//
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	//
	//  Private variables
	//
	//-------------------------------------------------------------------------

	/**
	 * @private
	 */
	private const _styleSheet:	StyleSheet = new StyleSheet();

	//-------------------------------------------------------------------------
	//
	//  Overridden methods: EventDispatcher
	//
	//-------------------------------------------------------------------------

	//-------------------------------------------------------------------------
	//
	//  Public methods
	//
	//-------------------------------------------------------------------------

	public function loadCSS(url:String):void {
		
	}

	public function addCSS(source:String):void {
		var tree:Cradle = new Cradle();

		const parser:CSSParser = new CSSParser();
		parser.addEventListener(Event.COMPLETE, this.handler_parseComplete);
		parser.parseCSS(source, tree);

		/*
		const styleSheet:StyleSheet = new StyleSheet();
		styleSheet.parseCSS(styleCSS);
		this._styleSheet.mergeStyleSheet(styleSheet);
		*/
	}

	private function handler_parseComplete(event:Event):void {
		var tree:Cradle = (event.target as CSSParser).tree;
	}
	
	private const _tables:Dictionary = new Dictionary( true );
	

	public function getStyleTable(component:UIComponent):StyleTable {
		// класс

		var qName:	QName = component.objectInfo.name;
		var key:	String = qName.toString();

		if ( !(key in this._tables) )
			this._tables[key] = new StyleTable();

		return this._tables[key];
	}


	/**
	 * Возвращает объект стилей для заданного AS3.0-класса (аналог CSS Type Selector)
	 * @param objectInfo
	 * @return Style object
	 * 
	 */
	public function getStyleByTypeSelector(objectInfo:ObjectInfo):Object {
		if ( !objectInfo )
			return null;

		var resultStyle:	Object = {};
		var ancestors:		Array = objectInfo.getSuperclasses().reverse();

		for (var i:uint = 0; i < ancestors.length; i++) {
			var arr:Array = String( ancestors[i] ).split('::');
			var className:String = arr[1] || arr[0];
			var style:Object = this._styleSheet.getStyle( className.toLowerCase() );

			for (var styleName:String in style) {
				resultStyle[styleName] = style[styleName];
			}
		}

		return resultStyle;
	}

	/**
	 * Возвращает объект стилей для заданного селектора класса (styleName attribute) 
	 * (аналог CSS Class Selector)
	 * 
	 * @param classSelector
	 * @return Style object
	 * 
	 */
	public function getStyleByClassSelector(classSelector:String):Object {
		if ( !classSelector )
			return null;

		classSelector = '.' + classSelector;

		return this._styleSheet.getStyle(classSelector);
	}

	/**
	 * Возвращает объект стилей наследуемого селектора(ов) для предоставленной цепочки объектов
	 * (объединенный стиль для descendant-selectors)
	 * 
	 * @param ancestorChain
	 * @return Style object
	 * 
	 */
	public function getStyleDescendantSelectors(ancestorChain:Array):Object {
		if ( !ancestorChain )
			return null;

		const chain:String = ancestorChain.join(',');

		return null;
	}

	//-------------------------------------------------------------------------
	//
	//  Private methods
	//
	//-------------------------------------------------------------------------

}
}
